﻿using System;
using System.Configuration;

namespace Globsite.Globalization.Mvc.DbResources.Repositories
{
    public interface IRepositoryFactory
    {
        RepositoryBase CreateRepository();

        RepositoryBase CreateRepository(ConnectionStringSettings connectionStringSettings, string resourceTable, bool ignoreCase = false);
    }

    public class RepositoryFactory : IRepositoryFactory
    {
        public RepositoryBase CreateRepository()
        {
            var connectionStringSettings = ConfigurationManager.ConnectionStrings[GlobsiteConfigSection.Instance.DbResources.ConnectionStringName];
            var resourceTable = GlobsiteConfigSection.Instance.DbResources.ResourceTableName;
            var ignoreCase = GlobsiteConfigSection.Instance.DbResources.IgnoreCase;

            return CreateRepository(connectionStringSettings, resourceTable, ignoreCase);
        }

        public RepositoryBase CreateRepository(ConnectionStringSettings connectionStringSettings, string resourceTable, bool ignoreCase = false)
        {
            if (connectionStringSettings == null)
                throw new NullReferenceException("The connection string settings cannot be null.");
            if (string.IsNullOrEmpty(resourceTable))
                throw new NullReferenceException("The resource table name cannot be null or empty.");

            switch (connectionStringSettings.ProviderName)
            {
                case "System.Data.SqlClient":
                    return new SqlServerRepository { ConnectionString = connectionStringSettings.ConnectionString, ResourceTable = resourceTable, IgnoreCase = ignoreCase };
                default:
                    throw new UnsupportedProviderException(string.Format("The '{0}' provider is not supported. Please go to the documentation for a list of all supported providers.", connectionStringSettings.ProviderName));
            }
        }
    }
}
